import java.util.ArrayList;
import java.util.List;

class Solution {
    private int[] tmpNums;
    private int[] tmpIndex;
    private int[] index;
    public List<Integer> countSmaller(int[] nums) {
        int len = nums.length;
        tmpNums = new int[len];
        tmpIndex = new int[len];
        index = new int[len];
        for(int i = 0; i < len; i++){
            index[i] = i;
        }
        int[] ret = new int[len];
        mergeSort(nums, 0, len - 1, ret);
        List<Integer> res = new ArrayList<>();
        for(int i = 0; i < len; i++){
            res.add(ret[i]);
        }
        return res;
    }
    private void mergeSort(int[] nums, int left, int right, int[] ret){
        if(left >= right) return;
        int mid = (left + right) / 2;
        mergeSort(nums, left, mid, ret);
        mergeSort(nums, mid + 1, right, ret);
        //合并两个有序数组
        merge(nums, left, mid, right, ret);
    }
    private void merge(int[] nums, int left, int mid, int right, int[] ret){
        int s1 = left;
        int s2 = mid + 1;
        int cur = 0;
        //采用降序的策略
        while(s1 <= mid && s2 <= right){
            if(nums[s1] > nums[s2]){
                tmpNums[cur] = nums[s1];
                tmpIndex[cur] = index[s1];
                ret[index[s1]] += right - s2 + 1;
                cur++;
                s1++;
            }else{
                tmpNums[cur] = nums[s2];
                tmpIndex[cur] = index[s2];
                cur++;
                s2++;
            }
        }
        while(s1 <= mid){
            tmpNums[cur] = nums[s1];
            tmpIndex[cur++] = index[s1++];
        }
        while(s2 <= right){
            tmpNums[cur] = nums[s2];
            tmpIndex[cur++] = index[s2++];
        }
        //合并完成，再放回原数组
        for(int i = left; i <= right; i++){
            nums[i] = tmpNums[i - left];
            index[i] = tmpIndex[i - left];
        }
    }
}